import {
  ajax
} from "../../utils/index";

// pages/creator/creator.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    author: '',
    text: '',
    cover: [],
    aboutSystem: 'HarmonyOS',
  },

  uploadImg() {
    let {
      cover
    } = this.data;
    wx.chooseMedia({
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const {
          tempFiles
        } = res;

        tempFiles.forEach(item => {
          wx.uploadFile({
            url: 'https://iplay666.fun/uploadImg',
            filePath: item.tempFilePath,
            name: 'file',
            success: (res) => {
              const {
                data
              } = res;
              let {
                path
              } = JSON.parse(data)[0];
              console.log(path);
              let __path = path.split('\\');
              let _path = `https://iplay666.fun/${__path[0]}`;
              cover.unshift(_path);
              this.setData({
                cover
              })
            },
            fail: (err) => {
              console.log(err);
            }
          })
        })


      }
    })
  },


  topublish: async function () {
    const {
      title,
      author,
      cover,
      text,
      aboutSystem,
    } = this.data;
    if (!title || !author || !text || !aboutSystem || !cover) {
      wx.showToast({
        title: '有内容未填写',
        icon: 'none',
      });
      return;
    }
    const params = {
      title,
      author,
      cover,
      text,
      aboutSystem,
      createTime: new Date().getTime(),
      updateTime: new Date().getTime(),
    }
    const result = await ajax('/publish', 'POST', params);
    const {
      data
    } = result;
    if (data === "success") {
      wx.switchTab({
        url: '../my/my',
        success: () => {
          wx.showToast({
            title: '上传成功',
            icon: 'none'
          })
        }
      })
    } else {
      wx.showToast({
        title: '发布失败',
        icon: 'none'
      })
    }
  },


  onChangetitle(event) {
    this.setData({
      title: event.detail
    })
  },

  onChangeauthor(event) {
    this.setData({
      author: event.detail
    })
  },

  onChangetext(event) {
    this.setData({
      text: event.detail.value
    })
  },

  onChangeSelected(event) {
    this.setData({
      aboutSystem: event.detail,
    });
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})